'use strict';

const db = uniCloud.database();

/**
 * 热门播放列表云对象
 * @description 提供热门播放列表的管理功能
 */
module.exports = {
  _before: function () {
    // 通用预处理器
    this.startTime = Date.now();
  },

  /**
   * 获取热门播放列表
   * @param {number} limit 获取数量，默认10条
   * @returns {object} 热门播放列表
   */
  async getFeaturedPlaylists(limit = 10) {
    try {
      // 确保limit是整数
      limit = parseInt(limit, 10);
      if (isNaN(limit) || limit <= 0) {
        limit = 10;
      }
      
      const playlistCollection = db.collection('sh_featured_playlist');
      
      // 查询激活的播放列表
      const result = await playlistCollection
        .where({ is_active: true })
        .orderBy('sort_order', 'asc')
        .limit(limit)
        .get();
      
      if (result.data && result.data.length > 0) {
        // 遍历每个播放列表，获取图案计数和处理背景色
        const playlists = await Promise.all(
          result.data.map(async (playlist) => {
            // 获取图案数量
            const patternCount = playlist.patterns ? playlist.patterns.length : 0;
            
            // 处理颜色设置
            let background = playlist.background_color || '';
            if (!background) {
              // 如果没有设置背景色，根据类型设置默认颜色
              switch (playlist.playlist_type) {
                case 'nature':
                  background = 'linear-gradient(135deg, #2CCCFF, #20B4F9)';
                  break;
                case 'art':
                  background = 'linear-gradient(135deg, #FF61D2, #BD34FE)';
                  break;
                case 'abstract':
                  background = 'linear-gradient(135deg, #13E2DA, #01A38B)';
                  break;
                case 'geometry':
                  background = 'linear-gradient(135deg, #FF9A44, #FC6076)';
                  break;
                default:
                  background = 'linear-gradient(135deg, #4080ff, #0055ff)';
              }
            }
            
            return {
              id: playlist._id,
              title: playlist.playlist_name,
              title_en: playlist.playlist_name_en,
              type: playlist.playlist_type,
              count: patternCount,
              description: playlist.description,
              background: background,
              cover_image: playlist.cover_image,
              sort_order: playlist.sort_order
            };
          })
        );
        
        return {
          errCode: 0,
          errMsg: 'success',
          data: playlists
        };
      } else {
        // 返回默认列表
        return {
          errCode: 0,
          errMsg: 'No featured playlists found, returning default',
          data: [
            { id: 'nature', title: '自然风景', count: 23, type: 'nature', background: 'linear-gradient(135deg, #2CCCFF, #20B4F9)' },
            { id: 'art', title: '艺术', count: 15, type: 'art', background: 'linear-gradient(135deg, #FF61D2, #BD34FE)' },
            { id: 'abstract', title: '抽象', count: 12, type: 'abstract', background: 'linear-gradient(135deg, #13E2DA, #01A38B)' },
            { id: 'geometry', title: '几何', count: 18, type: 'geometry', background: 'linear-gradient(135deg, #FF9A44, #FC6076)' }
          ]
        };
      }
    } catch (error) {
      console.error('获取热门播放列表失败:', error);
      return {
        errCode: 'GET_FEATURED_PLAYLISTS_FAILED',
        errMsg: '获取热门播放列表失败: ' + error.message
      };
    }
  },
  
  /**
   * 获取播放列表详情
   * @param {string} playlist_id 播放列表ID
   * @returns {object} 播放列表详情
   */
  async getPlaylistDetail(param) {
	
	let playlist_id = param.id
    if (!playlist_id) {
      return {
        errCode: 'PARAM_ERROR',
        errMsg: '缺少必要参数：playlist_id'
      };
    }
    
    try {
      const playlistCollection = db.collection('sh_featured_playlist');
      const patternCollection = db.collection('sh_pattern');
      const cmd = db.command;
      
      // 查询播放列表
      const playlist = await playlistCollection.doc(playlist_id).get();
      
      if (!playlist.data || playlist.data.length === 0) {
        return {
          errCode: 'PLAYLIST_NOT_FOUND',
          errMsg: '播放列表不存在'
        };
      }
      
      const playlistData = playlist.data[0];
      
      // 如果有关联的图案列表，查询图案详情
      if (playlistData.patterns && playlistData.patterns.length > 0) {
        // 提取所有图案ID
        const patternIds = playlistData.patterns;
        
        // 查询所有相关图案
        const patterns = await patternCollection
          .where({
            _id: cmd.in(patternIds)
          })
          .field({
            _id: true,
            pattern_name: true,
            pattern_name_en: true,
            preview_image: true,
            pattern_file: true,
            category: true,
            duration: true,
            favorite_count: true,
            download_count: true,
            difficulty: true
          })
          .get();
        
        // 将图案数据与排序信息合并
        const sortMap = {};
        playlistData.patterns.forEach(p => {
          sortMap[p.pattern_id] = p.sort_order;
        });
        
        // 根据sort_order排序
        const sortedPatterns = patterns.data.map(p => ({
          ...p,
          sort_order: sortMap[p._id] || 0
        })).sort((a, b) => a.sort_order - b.sort_order);
        
        return {
          errCode: 0,
          errMsg: 'success',
          data: {
            playlist: {
              id: playlistData._id,
              title: playlistData.playlist_name,
              title_en: playlistData.playlist_name_en,
              type: playlistData.playlist_type,
              description: playlistData.description,
              background: playlistData.background_color,
              cover_image: playlistData.cover_image
            },
            patterns: sortedPatterns
          }
        };
      }
      
      // 没有关联图案的情况
      return {
        errCode: 0,
        errMsg: 'success',
        data: {
          playlist: {
            id: playlistData._id,
            title: playlistData.playlist_name,
            title_en: playlistData.playlist_name_en,
            type: playlistData.playlist_type,
            description: playlistData.description,
            background: playlistData.background_color,
            cover_image: playlistData.cover_image
          },
          patterns: []
        }
      };
    } catch (error) {
      console.error('获取播放列表详情失败:', error);
      return {
        errCode: 'GET_PLAYLIST_DETAIL_FAILED',
        errMsg: '获取播放列表详情失败: ' + error.message + JSON.stringify(playlist_id)
      };
    }
  },
  
  /**
   * 添加图案到播放列表（管理员使用）
   * @param {string} playlist_id 播放列表ID
   * @param {string} pattern_id 图案ID
   * @param {number} sort_order 排序顺序，默认为0
   * @returns {object} 操作结果
   */
  async addPatternToPlaylist(playlist_id, pattern_id, sort_order = 0) {
    // 获取当前用户身份
    const { uid, role } = this.ctx.auth;
    if (!uid || (role && !role.includes('admin'))) {
      return {
        errCode: 'PERMISSION_DENIED',
        errMsg: '权限不足'
      };
    }
    
    try {
      if (!playlist_id || !pattern_id) {
        return {
          errCode: 'PARAM_ERROR',
          errMsg: '缺少必要参数：playlist_id 或 pattern_id'
        };
      }
      
      const playlistCollection = db.collection('sh_featured_playlist');
      const patternCollection = db.collection('sh_pattern');
      
      // 查询播放列表
      const playlist = await playlistCollection.doc(playlist_id).get();
      if (!playlist.data || playlist.data.length === 0) {
        return {
          errCode: 'PLAYLIST_NOT_FOUND',
          errMsg: '播放列表不存在'
        };
      }
      
      // 检查图案是否存在
      const pattern = await patternCollection.doc(pattern_id).get();
      if (!pattern.data || pattern.data.length === 0) {
        return {
          errCode: 'PATTERN_NOT_FOUND',
          errMsg: '图案不存在'
        };
      }
      
      // 获取现有图案列表
      const patterns = playlist.data[0].patterns || [];
      
      // 检查图案是否已在列表中
      const existingPatternIndex = patterns.findIndex(p => p.pattern_id === pattern_id);
      if (existingPatternIndex !== -1) {
        // 更新现有图案的排序
        patterns[existingPatternIndex].sort_order = sort_order;
      } else {
        // 添加新图案
        patterns.push({
          pattern_id,
          sort_order
        });
      }
      
      // 更新播放列表
      await playlistCollection.doc(playlist_id).update({
        patterns: patterns,
        update_time: new Date()
      });
      
      return {
        errCode: 0,
        errMsg: '添加图案成功',
        data: { patterns }
      };
    } catch (error) {
      console.error('添加图案到播放列表失败:', error);
      return {
        errCode: 'ADD_PATTERN_TO_PLAYLIST_FAILED',
        errMsg: '添加图案到播放列表失败: ' + error.message
      };
    }
  },
  
  /**
   * 从播放列表移除图案（管理员使用）
   * @param {string} playlist_id 播放列表ID
   * @param {string} pattern_id 图案ID
   * @returns {object} 操作结果
   */
  async removePatternFromPlaylist(playlist_id, pattern_id) {
    // 获取当前用户身份
    const { uid, role } = this.ctx.auth;
    if (!uid || (role && !role.includes('admin'))) {
      return {
        errCode: 'PERMISSION_DENIED',
        errMsg: '权限不足'
      };
    }
    
    try {
      if (!playlist_id || !pattern_id) {
        return {
          errCode: 'PARAM_ERROR',
          errMsg: '缺少必要参数：playlist_id 或 pattern_id'
        };
      }
      
      const playlistCollection = db.collection('sh_featured_playlist');
      
      // 查询播放列表
      const playlist = await playlistCollection.doc(playlist_id).get();
      if (!playlist.data || playlist.data.length === 0) {
        return {
          errCode: 'PLAYLIST_NOT_FOUND',
          errMsg: '播放列表不存在'
        };
      }
      
      // 获取现有图案列表
      const patterns = playlist.data[0].patterns || [];
      
      // 移除指定图案
      const updatedPatterns = patterns.filter(p => p.pattern_id !== pattern_id);
      
      // 更新播放列表
      await playlistCollection.doc(playlist_id).update({
        patterns: updatedPatterns,
        update_time: new Date()
      });
      
      return {
        errCode: 0,
        errMsg: '移除图案成功',
        data: { patterns: updatedPatterns }
      };
    } catch (error) {
      console.error('从播放列表移除图案失败:', error);
      return {
        errCode: 'REMOVE_PATTERN_FROM_PLAYLIST_FAILED',
        errMsg: '从播放列表移除图案失败: ' + error.message
      };
    }
  },
  
  _after(error, result) {
    if (error) {
      throw error;
    }
    return result;
  }
};
